package com.storeapp.ui;

import java.util.ArrayList;
import java.util.List;


import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;


import com.storeapp.entity.domain.DealOrder;
import com.storeapp.service.DealOrderService;
import com.storeapp.util.SpringUtils;

public class OrderList extends ViewPart implements IPropertyChangeListener {
	public static final String ID = "com.storeapp.ui.OrderList";
	
	private ListViewer lv;
	private List<DealOrder> orders;
	private DealOrderService dealOrderService;
	
	class ViewContentProvider implements IStructuredContentProvider {		
		@Override
		public void dispose() {
			// TODO Auto-generated method stub
		}
		@Override
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
			// TODO Auto-generated method stub
		}
		@SuppressWarnings("unchecked")
		@Override
		public Object[] getElements(Object inputElement) {
			// TODO Auto-generated method stub
			List<DealOrder> list = (List<DealOrder>) inputElement;
			return list.toArray();
		}		
	}
	
	class ViewLabelProvider extends LabelProvider {
		public String getText(Object obj) {
			DealOrder dealOrder = (DealOrder)obj;
			return dealOrder.getPurchaseDate().toString()+"//"+dealOrder.getTotalPrice();
		}
	}

	public OrderList(){
		super();
		this.orders = new ArrayList<DealOrder>();
		dealOrderService = (DealOrderService) SpringUtils
		.getApplicationContext().getBean("dealOrderService");
	}
	
	@Override
	public void createPartControl(Composite parent) {
		// TODO Auto-generated method stub
		lv = new ListViewer(parent, SWT.BORDER | SWT.V_SCROLL);
		lv.setContentProvider(new ViewContentProvider());
		lv.setLabelProvider(new ViewLabelProvider());
		orders = this.dealOrderService.listAll();
		lv.setInput(orders);
		
		getSite().setSelectionProvider(lv);
	}

	@Override
	public void propertyChange(PropertyChangeEvent event) {
		// TODO Auto-generated method stub
		if( event.getProperty().equals("AddNewOrder")) {
			orders.clear();
			orders.addAll(dealOrderService.listAll());
			lv.refresh();
		}
	}
	
	@Override
	public void setFocus() {
		// TODO Auto-generated method stub
		lv.getControl().setFocus();
	}
}
